package com.tarena.lbs.activity.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarena.lbs.activity.dao.mapper.ActivityMapper;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;

@Slf4j
@Repository
public class ActivityRepositoryImpl implements ActivityRepository {
    @Autowired
    private ActivityMapper activityMapper;


    @Override
    public Page<ActivityPO> pageList(ActivityQuery activityQuery) {
        // 创建分页对象
        Page<ActivityPO> page = new Page<>(activityQuery.getPageNo(), activityQuery.getPageSize());
        // 构建查询条件
        QueryWrapper<ActivityPO> queryWrapper = generateQuery(activityQuery);
        // 执行分页查询
        return activityMapper.selectPage(page, queryWrapper);
    }

    @Override
    public void updateActivity(ActivityPO activityPO) {
        activityPO.setUpdateAt(new Date());
        activityMapper.updateById(activityPO);
    }

    @Override
    public void insertActivity(ActivityPO activityPO) {
        activityPO.setCreateAt(new Date());
        activityMapper.insert(activityPO);
    }

    @Override
    public ActivityPO activityDetail(Integer id) {
        log.info("查询活动详情仓储层，活动id：{}", id);
        return activityMapper.selectById(id);
    }


    /**
     * 查询字段映射工具方法
     * @param activityQuery
     * @return
     */
    private QueryWrapper<ActivityPO> generateQuery(ActivityQuery activityQuery) {
        QueryWrapper<ActivityPO> wrapper = new QueryWrapper<>();
        if (activityQuery.getActivityName() != null && !"".equals(activityQuery.getActivityName())) {
            wrapper.like("activity_name", activityQuery.getActivityName());
        }
        if (activityQuery.getStatus() != null) {
            wrapper.eq("status", activityQuery.getStatus());
        }
        if (activityQuery.getType() != null) {
            wrapper.eq("activity_type", activityQuery.getType());
        }
        if (activityQuery.getChannelType() != null) {
            wrapper.eq("channel_type", activityQuery.getChannelType());
        }
        if (activityQuery.getStartDate() != null) {
            wrapper.ge("start_date", activityQuery.getStartDate());
        }
        if (activityQuery.getEndDate() != null) {
            wrapper.le("end_date", activityQuery.getEndDate());
        }
        if (activityQuery.getDeliveryChannel() != null) {
            wrapper.eq("deliver_channel", activityQuery.getDeliveryChannel());
        }

        // 添加排序字段（可选）
        wrapper.orderByDesc("create_at").orderByDesc("id");

        return wrapper;
    }

}
